<template>
  <div class="basic-score-config">
    <SearchTable
      :columns="columns" 
      :data="list"
      :total="total"
      :page.sync="currentPage"
      :size.sync="pageSize"
      @queryFun="getTeamBasicList"
    >
      <template slot="button-group">
        <Button
          v-if="type !== 5"
          type="primary"
          ghost
          @click="showModal = true"
          icon="ios-options"
          :disabled="disabledAllBtn || drillStatus !== 1"
          >设置基础分</Button
        >
      </template>
      <template slot="select-group">
        <Select filterable
          v-if="type !== 5"
          v-model="teamName"
          placeholder="请选择团队"
          filterable
          clearable
          @on-change="changePage(1)"
        >
          <Option v-for="item in teamList" :value="item.name" :key="item.id" :title="item.name">{{
            item.name
          }}</Option>
        </Select>
        <Input v-model="teamName" v-if="type !== 0" placeholder="单位" @on-change="debounceSearch" clearable></Input>
      </template>
    </SearchTable>
    <Modal v-model="showModal" width="800" title="设置基础分" @on-ok="automationConfig">
      <Form ref="form" :model="formData" :rules="rules" :label-width="70">
        <FormItem label="基础分" prop="basicScore">
          <InputNumber
            :min="1"
            :max="9999"
            v-model="formData.basicScore"
            placeholder="基础分范围1~99999"
            style="width: 100%;"
          ></InputNumber>
        </FormItem>
      </Form>
      <div slot="footer" class="footer">
        <Button type="text" size="large" @click="showModal = false">取消</Button>
        <Button type="primary" size="large" @click="automationConfig" :loading="loading"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import SearchTable from '@/components/SearchTable/SearchTable';
import groupMixin from '@/mixin/groupMixin';
import { getTeamBasicList, updateTeamBasic, updateCompanyBasic } from '@/api/drill_compete';
import { debounce } from '@/libs/utils';
export default {
  name: 'basicScoreConfig',
  mixins: [groupMixin],
  props: {
    disabledAllBtn: {
      // 是否禁用按钮
      type: Boolean,
      default: false
    },
    drillStatus: {
      // 竞赛状态（1:准备中；2:进行中；3:已结束）
      type: Number,
      default: 1
    },
    type: {
      type: Number,
      required: true
    }
  },
  components: {
    SearchTable
  },
  data() {
    const validateScore = (rule, value, callback) => {
      if (value !== 0 && !value) {
        callback(new Error('不能为空'));
        return;
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入整数'));
        return;
      }
      if (value <= 0 || value > 100000) {
        callback(new Error('请输入1-100000的整数'));
        return;
      }
      callback();
    };
    return {
      loading: false,
      rules: {
        basicScore: [
          { required: true, type: 'number', message: '不能为空', trigger: 'change' },
          { validator: validateScore, trigger: 'change' }
        ]
      },
      formData: {
        basicScore: 1000
      },
      showModal: false,
      columns: [
        {
          placement: 'top-left',
          title: this.type !== 5 ? '团队名称' : '单位',
          key: 'teamName',
          align: 'center',
          tooltip: true,
          width: 230
        },
        {
          title: '基础分',
          width: 80,
          key: 'basicScore'
        },
        {
          title: '剩余分',
          width: 80,
          key: 'lastScore',
          show: this.type !== 5 ? true : false
        },
        {
          title: '创建时间',
          width: 140,
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'os',
          ellipsis: true,
          width: 200,
          placement: 'top-right',
          action: true,
          show: this.type !== 5 ? false : true,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small',
                    disabled: this.disabledAllBtn || this.drillStatus !== 1
                  },
                  style: {
                    border: 'none',
                    background: 'none',
                    boxShadow: 'none',
                    display: this.configMode === 1 ? 'none' : 'inline-block'
                  },
                  on: {
                    click: () => {
                      this.showModal = true;
                      this.currentId = params.row.id;
                      this.formData.basicScore = params.row.basicScore;
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src:
                        this.disabledAllBtn || this.drillStatus !== 1
                          ? require('../../../assets/project/modifys.png')
                          : require('../../../assets/project/modifys-h.png')
                    },
                    style: {
                      cursor: 'pointer',
                      'vertical-align': 'middle',
                      display: 'inline-block',
                      marginBottom: '4px'
                    }
                  })
                ]
              )
            ]);
          }
        }
      ],
      teamName: '', // 团队名称，搜索条件
      currentPage: 1, // 当前页
      pageSize: 10, // 分页大小
      total: 0, // 总记录数
      list: [] // 题目解答列表
    };
  },
  computed: {},
  mounted() {
    this.sceneId = this.$route.query.id;
    this.$nextTick(() => {
      this.getTeamBasicList();
    });
  },
  methods: {
    changePage(page){
      this.currentPage = page;
      this.getTeamBasicList();
    },
    // 获取基础分列表
    getTeamBasicList() {
      getTeamBasicList({
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        teamName: this.teamName,
        sceneId: this.sceneId
      })
        .then(({ code, data, message }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.total = data.total || 0;
          this.list = data.items || [];
        })
        .catch((error) => {
          this.$Message.error('获取团队基础分异常');
        });
    },
    debounceSearch: debounce(function() {
      this.changePage(1);
    }, 500),
    // 一键配置基础分
    automationConfig() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          let apiReq;
          if (this.type !== 5 ) {
            apiReq = updateTeamBasic({
              sceneId: this.sceneId,
              basicScore: this.formData.basicScore
            });
          } else {
            apiReq = updateCompanyBasic(this.currentId, {
              basicScore: this.formData.basicScore
            });
          }
          apiReq
            .then(({ code, message }) => {
              if (code !== 1) {
                this.$Message.warning(message);
                return;
              }
              this.$Message.info('设置基础分成功');
              this.resetData();
              this.getTeamBasicList();
              this.showModal = false;
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    resetData() {
      this.currentPage = 1;
      this.pageSize = 10;
      this.teamName = '';
    }
  },
  beforeDestroy() {},
  watch: {
    showModal(val) {
      if (!val) {
        this.formData.basicScore = 1000;
      }
    }
  }
};
</script>

<style scoped></style>
